/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kunzisoft.switchdatetimesample.slice;

import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import com.kunzisoft.switchdatetimesample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.text.SimpleDateFormat;
import java.util.*;

public class MainAbilitySlice extends AbilitySlice {
    private static final String TAG = "Sample";

    private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";

    private static final String STATE_TEXTVIEW = "STATE_TEXTVIEW";
    private Text textView;

    private SwitchDateTimeDialogFragment dateTimeFragment;
    private Preferences mOrientation;
    private Preferences mTimeDataSave;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        // 创建轻量级数据存储
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        mOrientation = databaseHelper.getPreferences("ori_pref");
        mTimeDataSave = databaseHelper.getPreferences("time_pref");

        // 通过获取屏幕宽高来间接判断当前横竖屏情况，getDisplayOrientation()无法获取到横竖屏
        Display display = DisplayManager.getInstance().getDefaultDisplay(this).get();
        if (display.getAttributes().width > display.getAttributes().height) {
            // 判断为横屏，保存
            mOrientation.putBoolean("orientation", false);
        } else {
            // 判断为竖屏，保存
            mOrientation.putBoolean("orientation", true);
        }

        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(Color.getIntColor("#b71c1c"));
        textView = (Text) findComponentById(ResourceTable.Id_textView);
        // Construct SwitchDateTimePicker
        dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
                getAbility(),
                getString(ResourceTable.String_label_datetime_dialog),
                "OK",
                "Cancel",
                getString(ResourceTable.String_clean) // Optional
        );

        // Optionally define a timezone
        dateTimeFragment.setTimeZone(TimeZone.getDefault());

        // Init format
        final SimpleDateFormat myDateFormat = new SimpleDateFormat("d MMM yyyy HH:mm", java.util.Locale.getDefault());
        // Assign unmodifiable values
        dateTimeFragment.set24HoursMode(false);
        dateTimeFragment.setHighlightAMPMSelection(false);
        dateTimeFragment.setMinimumDateTime(new GregorianCalendar(2015, Calendar.JANUARY, 1).getTime());
        dateTimeFragment.setMaximumDateTime(new GregorianCalendar(2025, Calendar.DECEMBER, 31).getTime());

        // Define new day and month format
        try {
            dateTimeFragment.setSimpleDateMonthAndDayFormat(new SimpleDateFormat("MMMM dd", Locale.getDefault()));
        } catch (SwitchDateTimeDialogFragment.SimpleDateMonthAndDayFormatException e) {

            e.fillInStackTrace();
        }

        // Set listener for date
        dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonWithNeutralClickListener() {
            @Override
            public void onPositiveButtonClick(Date date) {
                textView.setText(myDateFormat.format(date));
            }

            @Override
            public void onNegativeButtonClick(Date date) {
                // Do nothing
            }

            @Override
            public void onNeutralButtonClick(Date date) {
                // Optional if neutral button does'nt exists
                textView.setText("");
            }
        });

        Button buttonView = (Button) findComponentById(ResourceTable.Id_button);
        buttonView.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component view) {
                if (mTimeDataSave != null){
                    mTimeDataSave.putInt("positionView", 1);
                }

                // Re-init each time
                dateTimeFragment.startAtCalendarView();
                dateTimeFragment.setDefaultDateTime(new GregorianCalendar(2017, Calendar.MARCH, 4, 15, 20).getTime());
                dateTimeFragment.show();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        System.out.println("-->>onOrientationChanged = " + displayOrientation);

        if (AbilityInfo.DisplayOrientation.LANDSCAPE == displayOrientation) {
            mOrientation.putBoolean("orientation", false);
        } else if (AbilityInfo.DisplayOrientation.PORTRAIT == displayOrientation) {
            mOrientation.putBoolean("orientation", true);
        }

        boolean s = false;
        if (dateTimeFragment.isShowing()) {
            dateTimeFragment.destroy();
            s = true;
        }

        // 刷新ability
        onStart(null);

        if (s) {
            // 重新show dialog
            System.out.println("-->>onOrientationChanged = " + mTimeDataSave.getInt("month", 2));
            dateTimeFragment.setDefaultDateTime(new GregorianCalendar(
                    mTimeDataSave.getInt("year", 2017),
                    mTimeDataSave.getInt("month", 2),
                    mTimeDataSave.getInt("day", 4),
                    mTimeDataSave.getInt("hour", 15),
                    mTimeDataSave.getInt("minute", 20)).getTime());
            dateTimeFragment.show();
        }
    }
}
